package handler.server;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

/**
 * @author dfj@99chuxing.com
 * @date 2018/3/28 0028 15:51
 */
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

    private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled
            .unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat",
                    CharsetUtil.UTF_8));


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ByteBuf  byteBuf=(ByteBuf)msg;
                    System.out.println(byteBuf);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                        IdleStateEvent idleStateEvent =(IdleStateEvent)evt;
                        if (idleStateEvent.state()== IdleState.READER_IDLE){
                            /** 心跳时间内 ，没有数据接收，读超时*/
                            System.out.println("心跳时间内 ，没有数据接收，读超时");
                            // 关闭通道
                            ctx.channel().close();
                            ctx.close();
                            // 将会阻塞等待直到服务器的 Channel关闭
                        }
                        if (idleStateEvent.state()==IdleState.WRITER_IDLE){
                            /** 心跳时间内, 没有数据发送 */

                        }

            } else {
                        super.userEventTriggered(ctx, evt);
            }

    }
}
